/*
 * @Description: 路由转发
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-05-19 16:00:42
 * @LastEditTime: 2022-06-06 14:26:18
 */
import Koa from 'koa'
import Router from '@koa/router'
import Micro from 'tcp-micro-service'
import serviceClient from './serviceClient.js'
import parseFileData from './parseFileData.js'

interface IRouterCtx extends Koa.ParameterizedContext<any, Router.RouterParamContext<any, {}>, any> {
    micro?: Micro
}

// 创建路由实例
const router = new Router()

// 路由转发
router.all(
    '/api/:service/:path',
    serviceClient(), // 服務鏈接
    parseFileData(), // 文件数据整理
    async (ctx: IRouterCtx) => {
        const { service, path } = ctx.params
        const { method, header } = ctx.request
        // header需传 'access-token'、'token'


        console.log("==ctx.query", ctx.query)
        console.log("==ctx.request.body", ctx.request.body)

        // timeout
        // responseType:'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
        // headers: { 'content-type': 'application/x-www-form-urlencoded' } multipart/form-data、application/json

        // 请求
        const res = await ctx.micro.request({
            service,
            path,
            method,
            data: method.toLowerCase() === 'get' ? ctx.query : ctx.request.body,
            header
        })

        if (res.ok === -1) {
            ctx.status = res.status
        }

        ctx.body = res
    })

export default router